﻿/************************************************************************

   Extended Silverlight Toolkit

   Copyright (C) 2010-2012 Xceed Software Inc.

   This program is provided to you under the terms of the Microsoft Public
   License (Ms-PL) as published at http://extendedsilverlight.codeplex.com/license

   Please purchase a commercial version of this toolkit if you are using
   it in a commercial product. The commercial versions support the project,
   and also include more features for each control, priority support,
   source code, updates, removed watermark, and a proprietary license.

   Visit http://xceed.com and follow @datagrid on Twitter.

  **********************************************************************/

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Reflection;

namespace Xceed.Silverlight.DataGrid.Utils
{
  public class AttachedPropertyHelper
  {
    static internal Binding CreateAttachedPropertyBinding( Type ownerType, string ownerProperty, bool isAttached )
    {
      DependencyProperty dependencyProperty;
      return AttachedPropertyHelper.CreateAttachedPropertyBinding( ownerType, ownerProperty, isAttached, out dependencyProperty );
    }

    static internal Binding CreateAttachedPropertyBinding( Type ownerType, string ownerProperty, bool isAttached, out DependencyProperty dependencyProperty )
    {

      // Expecting a static DependencyProperty object with the same name ending with an "Property" suffix
      FieldInfo field = ownerType.GetField( ownerProperty + "Property", BindingFlags.Public | BindingFlags.Static );
      dependencyProperty = ( DependencyProperty )field.GetValue( null );

      const string presentationXmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
      const string productXmlns = "http://schemas.xceed.com/silverlight/xaml/datagrid";
      const string ownerXmlns = "l";
      string ownerTypeName = ownerType.Name;
      string ownerNameSpace = ownerType.Namespace;
      string pathStr = ( isAttached ) ? "({0}:{1}.{2})" : "{2}";
      pathStr = string.Format( pathStr, ownerXmlns, ownerTypeName, ownerProperty );

      string bindingXamlStr = string.Format( "<Binding xmlns=\"{0}\" xmlns:{1}=\"{2}\" Path=\"{3}\" />", presentationXmlns, ownerXmlns, productXmlns, pathStr );
      return ( Binding )Compatibility.CompatibilityUtils.XamlParse( bindingXamlStr );
    }
  }
}
